﻿@using Resource;
@{
    Layout = null;
}

<!DOCTYPE html>

<html>
<head>
    <meta name="viewport" content="width=device-width,initial-scale=1.0,maximum-scale=1.0,user-scalable=no" />
    <meta http-equiv="Expires" content="0">
    <meta http-equiv="Pragma" content="no-cache">
    <meta http-equiv="Cache-control" content="no-cache">
    <meta http-equiv="Cache" content="no-cache">
    @{ await Html.RenderPartialAsync("/Views/Shared/_LayoutScript.cshtml"); }
    @{ await Html.RenderPartialAsync("/Views/Shared/_StyleCss.cshtml"); }

    <link href="/css/WIPReport.css?v=@DateTime.Now.Ticks" rel="stylesheet" />
    <title>WIPReport</title>
    <style type="text/css">
        /*报表样式*/
        html, body {
            background: url(../images/ProcessCapacity/bgwhite.png) no-repeat;
            background-size: cover;
            font-size: .16rem;
            color: #ffffff;
            position: relative;
            width: 100%;
            height: 100%;
            font-family: myFirstFont !important;
            color: black;
        }

        .rightTop {
            background-color: #f7fdff;
        }

        .dropbtn, button {
            background-color: #0aa9cd;
        }

        #query > button {
            background-color: #0aa9cd;
            border: 2px solid #0aa9cd;
        }

        .dropdown-content {
            background-color: #12bed0;
        }

        .ZebraNo {
            background-color: #e8f1f9;
        }

        .ZebraTo {
            background-color: #ffffff;
        }

        .note {
            color: red;
            font-size: 0.15rem;
            font-weight: bolder;
        }
        /*END*/

        .truncate {
            max-width: 1.2rem;
            white-space: nowrap;
            overflow: hidden;
            text-overflow: ellipsis;
        }
    </style>
</head>
<body class="fill-parent" style="overflow-y: hidden; color: black;">
    <div class="main">
        <div class="header">
            <div class="header-left fl">
                <img src="/images/logo.png?v=@DateTime.Now.Ticks" class="scaled-image" draggable="false" oncontextmenu="return false;" ondragstart="return false;" />
            </div>
            <div class="btn">
                <spn>
                    <div id="query">
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Desktop</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" href=@Html.Raw($"https://dashboard.li.lumentuminc.net/API/DesktopApp/Dashboard.exe?v={DateTime.Now.Ticks}") download>@Label.Local</a>
                                <a class="menudropdown" href=@Html.Raw($"https://dashboard.li.lumentuminc.net/API/DesktopApp/Dashboard_lnk.zip?v={DateTime.Now.Ticks}") download>@Label.Shortcut</a>
                            </div>
                        </div>
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Data@Label.Datum</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" onclick="ModalShow('TestFailGroup')">@Label.Datum@Label.Maintain</a>
                                @*<a class="menudropdown" onclick="TestDataExport('TestData')">@Label.Data@Label.Export</a>*@
                                <a class="menudropdown" onclick="WIPReportExport('WIPReport')">@Label.Report@Label.Export</a>
                            </div>
                        </div>
                        <div class="dropdown">
                            <button class="dropbtn">@Label.Language</button>
                            <div class="dropdown-content">
                                <a class="menudropdown" onclick="setLanguageCookie('@Const.CNLANGUAGE')">@Label.Chinese</a>
                                <a class="menudropdown" onclick="setLanguageCookie('@Const.USLANGUAGE')">@Label.English</a>
                            </div>
                        </div>
                        <button class="modalBtn dimension">@Label.Full</button>
                    </div>
                </spn>
            </div>
            <div class="header-center fl">
                <div class="header-title"></div>
                <div class="header-img"></div>
            </div>
            <div class="header-right fl" id="time"></div>
            <div class="header-bottom fl"></div>
        </div>
        <div class="center">
            <div class="center-left fl">
                <div class="left-top rightTop border">
                    <div class="title note">@Label.Note_WIPReport</div>
                    <div id="board" class="chart">
                        <div class="query">
                            <select id="cmb_proj_code" placeholder="select proj_code">
                                <option value="">@Label.PleaseSelect</option>
                            </select>
                            <select id="cmb_product_code" placeholder="select product_code">
                                <option value="ALL" selected>@Label.ALL</option>
                                <option value="">@Label.PleaseSelect</option>
                            </select>
                            <select id="cmb_month" placeholder="select month">
                                <option value="">@Label.PleaseSelect</option>
                            </select>
                            <button id="btn_query" class="btn btn-primary  btn-sm col-md-12" type="button" onclick="Getdata()">@Label.Query</button>
                        </div>
                        <div id="table-container">
                            <table id="myTable" class="DataSheet" border="1" style="width: 100%; height: 100%;">
                                <thead><tr></tr></thead>
                                <tbody id="yield_tbody"></tbody>
                                <tfoot><tr></tr></tfoot>
                            </table>
                        </div>
                    </div>
                </div>
            </div>

        </div>
    </div>
    <!-- 模态框 -文件下载上传 -->
    <div class="modal" style=" color: white;">
        <div class="modal-content family">
            <span class="close" onclick="ModalClose('modal')">×</span>
            <p id="Item" class="modal-title">物料信息维护</p>
            <br>
            <div class="form-flex">
                <label>
                    物料信息:
                    <span><label><button type="submit" style="background-color: rgba(255, 255, 255, 0.15); " onclick="WipPartNoExport()"><span><img src="/images/ProcessCapacity/Excel.ico" alt="Excel" class="icon"></span>导出</button></label></span>
                    <span id="export"></span>
                </label>
                <span>
                    <label>信息导入:</label>&nbsp;
                    <span><input type="file" id="Template" name="Template" style="width:calc(100% - 0.78rem)" placeholder="Enter your Process"></span>
                </span>
                <label for="message">message:</label>
                <input type="text" id="message" name="message" placeholder="Enter your message">
                <button type="submit" style="font-weight: bold; height:0.5rem;" onclick="UploadExcel()">Submit</button>
            </div>
        </div>
    </div>

    <script type="text/javascript" href="?v=@DateTime.Now.Ticks">
        //模板初始化配置
        $(document).ready(function () {
            var whei = $(window).height();
            $("html").css({ fontSize: whei / 12.5 });
            $(window).resize(function () {
                if ($(".dimension").text() == "@Html.Raw(Label.Full)") {
                    var whei = $(window).height();
                    $("html").css({ fontSize: whei / 12.5 });
                }
                else {
                    var whei = $(window).width();
                    $("html").css({ fontSize: whei / 22 })
                }
            });

            /*当前时间*/
            function numberToUpperCase(number) {
                var uppercaseMonths = [
                    '一月', '二月', '三月', '四月', '五月', '六月',
                    '七月', '八月', '九月', '十月', '十一月', '十二月'
                ];
                return uppercaseMonths[number - 1];
            }
            var myDate = new Date();
            var result = numberToUpperCase(myDate.getMonth() + 1);
            $('.header-title').html("@Html.Raw(Label.Board_WIPReport)");
            function getTime() {
                var myDate = new Date();
                var myYear = myDate.getFullYear(); //年
                var myMonth = myDate.getMonth() + 1; //月
                var myToday = myDate.getDate(); //日
                var myDay = myDate.getDay(); //星期
                var myHour = myDate.getHours(); //小时
                var myMinute = myDate.getMinutes(); //分钟
                var mySecond = myDate.getSeconds(); //秒数
                var week = ['@Label.Sunday', '@Label.Monday', '@Label.Tuesday', '@Label.Wednesday', '@Label.Thursday', '@Label.Friday', '@Label.Saturday'];
                var nowTime;

                nowTime = myYear + '-' + fillZero(myMonth) + '-' + fillZero(myToday) + '&nbsp;&nbsp;' + fillZero(myHour) + ':' + fillZero(myMinute) + ':' + fillZero(mySecond) + '&nbsp;&nbsp;' + week[myDay] + '&nbsp;&nbsp;';
                $('#time').html(nowTime);
            };
            function fillZero(str) {
                var realNum;
                if (str < 10) {
                    realNum = '0' + str;
                } else {
                    realNum = str;
                }
                return realNum;
            }
            setInterval(getTime, 1000);

            // 设置全屏
            $('.dimension').on('click', function (e) {
                var element = document.documentElement;
                if ($(".dimension").text() == "@Html.Raw(Label.Full)") {
                    // 判断浏览器设备类型
                    if (element.requestFullscreen) {
                        element.requestFullscreen();
                    } else if (element.mozRequestFullScreen) {       //兼容火狐
                        element.mozRequestFullScreen();
                    } else if (element.webkitRequestFullscreen) {    //兼容谷歌
                        element.webkitRequestFullscreen();
                    } else if (element.msRequestFullscreen) {        //兼容IE
                        element.msRequestFullscreen();
                    }
                    $(".dimension").text("@Html.Raw(Label.Exit+Label.Full)");
                } else {
                    if (document.exitFullscreen) {
                        document.exitFullscreen();
                    } else if (document.mozCancelFullScreen) {
                        document.mozCancelFullScreen();
                    } else if (document.webkitCancelFullScreen) {
                        document.webkitCancelFullScreen();
                    } else if (document.msExitFullscreen) {
                        document.msExitFullscreen();
                    }
                    $(".dimension").text("@Html.Raw(Label.Full)");
                }
            });

            $('#btn_query').prop('disabled', true);
            $('#startdate').on('change', function () {
                var startDate = new Date($(this).val());
                var endDate = new Date($('#enddate').val());
                //设置结束时间字段的最小值为开始时间
                //$('#enddate').attr('min', $(this).val());
                startDate.setDate(startDate.getDate() + 1);
                var minEndDate = startDate.toISOString().split('T')[0];
                $('#enddate').attr('min', minEndDate);
                // 检查结束时间是否小于开始时间
                if (endDate < startDate) {
                    //结束时间字段的值设置为开始时间
                    $('#enddate').val($(this).val());
                }
            });
            $('#enddate').on('change', function () {
                var startDate = new Date($('#startdate').val());
                var endDate = new Date($(this).val());
                //设置开始时间字段的最大值为结束时间
                //$('#startdate').attr('max', $(this).val());
                endDate.setDate(endDate.getDate() - 1);
                var maxStartDate = endDate.toISOString().split('T')[0];
                $('#startdate').attr('max', maxStartDate);
                // 检查开始时间是否大于结束时间
                if (startDate > endDate) {
                    //开始时间字段的值设置为结束时间
                    $('#startdate').val($(this).val());
                }
            });
        });

        //Tab页签定时切换
        var Tabtimer;
        function TabInterval() {
            clearInterval(Tabtimer);
            //每隔5m执行一次
            Tabtimer = setInterval(function () {
                boarddata();
            }, 10 * 60 * 1000);
        }

        var ComboxAction = function () {
            var projectsele = $("#cmb_proj_code");
            var productcode = $("#cmb_product_code");
            var cmonth = $("#cmb_month");
            var pam = {};
            loadData(projectsele, api + '/ReportAction/GetWipProjCode', false);
            loadData(cmonth, api + '/ReportAction/GetWipMonth', true);
            projectsele.change(function () {
                pam.proj_code = $(this).val();
                loadData(productcode, api + '/ReportAction/GetWipProductCode', false);
            });

            var projcode = $("#projcode");
            var productcode = $("#cmb_product_code");
            loadData(projcode, api + '/ReportAction/GetWipProjCode', false);
            projcode.change(function () {
                pam.proj_code = $(this).val();
                loadData(productcode, api + '/ReportAction/GetWipProductCode', false);
            });
            function loadData(selectElement, url, boolean) {
                $.ajax({
                    type: "POST",
                    url: url,
                    data: pam,
                    dataType: "json",
                    async: false,
                    success: function (data) {
                        selectdata = data.ReturnData;
                        selectElement.empty();
                        if (selectdata.length <= 0) {
                            var option = "<option>@Html.Raw(Label.No+Label.Correlation+Label.Data)</option>";
                            selectElement.append(option);
                            return;
                        }
                        if (boolean) {
                            selectElement.append("<option value=''>@Html.Raw(Label.PleaseSelect)...</option>");
                        } else {
                            selectElement.append("<option value='ALL'>@Html.Raw(Label.ALL)</option>");
                        }
                        $.each(selectdata, function (key, value) {
                            selectElement.append($('<option>', {
                                value: value.value,
                                text: value.text
                            }));
                        });
                    }
                });
            }
        }

        $(function () {
            ComboxAction();
            setTimeout(function () {
                $('#cmb_proj_code').prop('selectedIndex', 0);
                $('#cmb_product_code').prop('selectedIndex', 0);
                $('#cmb_month').prop('selectedIndex', 1);
                Getdata();
            }, 500);
        })

        var Getdata = function () {
            boarddata();
            TabInterval();
        }

        var ModalShow = function (type) {
            $("#Item").text("物料信息维护");
            $(".modal").fadeIn();
        }

        var ExportType;
        var WipPartNoExport = function () {
            ExportType = "WIPPARTNO";
            var pam = {
                type: ExportType,
                proj_code: $('#cmb_proj_code').val() == "" ? "ALL" : $('#cmb_proj_code').val(),
                product_code: $('#cmb_product_code').val() == "" ? "ALL" : $('#cmb_product_code').val(),
                month: $('#cmb_month').val()
            };
            var url = api + "/ReportAction/GetErpWipPartNoExport?" + $.param(pam);
            ExportToExcel(url);
        }

        function ModalClose(modalname) {
            $("#export").empty();
            $("."+modalname+"").fadeOut();
        }

        //上传
        var UploadExcel = function () {
            var fileInput = document.getElementById("Template");
            var file = fileInput.files[0];
            var formData = new FormData();
            formData.append("file", file);
            formData.append("type", "WipPartNo");
            $.ajax({
                type: "POST",
                //url: "http://localhost:44304/Dashboard/UploadExcel",
                url: api + "/ReportAction/UploadExcel",
                enctype: 'multipart/form-data',
                data: formData,
                async: false,
                processData: false,// 禁止将数据转换为查询字符串
                contentType: false,// 禁止设置请求头的Content-Type
                crossDomain: true,
                success: function (data) {
                    if (data.Success) {
                        alert("successfully");
                        //$('#product').empty();
                        //$('#process').empty();
                        $("#Template").val('');
                        $("#message").val('');
                        $(".modal").fadeOut();
                    }
                }
            });

        };

        /*导出生产数据*/
        var TestDataExport = function (type) {
            ExportType = type;
            var formData = new FormData();
            formData.append('type', ExportType);
            formData.append('proj_code', $('#cmb_proj_code').val());
            formData.append('process_id', $('#cmb_process_code').val() == null ? "ALL" : $('#cmb_process_code').val());
            formData.append('start_time', $("#startdate").val());
            formData.append('end_time', $("#enddate").val());
            var url = api + "/Dashboard/TestDataToExcel";
            PostExportToExcel(url, formData);

        }
        //报表导出
        var WIPReportExport = function (type) {
            var formData = new FormData();
            formData.append('proj_code', $('#cmb_proj_code').val());
            formData.append('product_code', $("#cmb_product_code").val());
            formData.append('month', $("#cmb_month").val());
            ExportType = type;
            var url = api + "/ReportAction/ErpWipReportToExcel";
            PostExportToExcel(url, formData);
        }
        //POST 参数不固定 导出
        var PostExportToExcel = function (url, formData) {
            //GET: var url = "http://localhost:44304/Dashboard/ExportToExcel?" + $.param(pam);
            var xhr = new XMLHttpRequest();
            xhr.open('POST', url, true);
            xhr.responseType = 'blob';
            xhr.onload = function () {
                if (xhr.status === 200) {
                    var url = window.URL.createObjectURL(xhr.response);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = ExportType.toLocaleUpperCase() + '.xlsx';
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            };
            xhr.send(formData);
        }

        //导出
        var ExportToExcel = function (url) {
            //var url = "http://localhost:44304/Dashboard/ExportToExcel?" + $.param(pam);
            var xhr = new XMLHttpRequest();
            xhr.open('GET', url, true);
            xhr.responseType = 'blob';
            xhr.onload = function () {
                if (xhr.status === 200) {
                    var url = window.URL.createObjectURL(xhr.response);
                    var a = document.createElement('a');
                    a.href = url;
                    a.download = ExportType.toLocaleUpperCase() + '.xlsx';
                    a.click();
                    window.URL.revokeObjectURL(url);
                }
            };
            /*
            GET:param
            var formData = new FormData();
            formData.append('CL_TYPE', $("#cmb_classtype").val());
            xhr.send(formData);
            */
            xhr.send();
        }

        //合并相同行
        function mergeFunc(tableId) {
            var tab = document.getElementById(tableId);
            var maxCol = 3;//maxcol用于设置需要合并的列数
            var count, start;
            for (var col = maxCol - 1; col >= 0; col--) {
                //用于存储相同个数
                count = 1;
                for (var i = 0; i < tab.rows.length; i++) {
                    if (i > 0 && col > 0 && tab.rows[i].cells[col].innerHTML == tab.rows[i - 1].cells[col].innerHTML
                        && tab.rows[i].cells[col - 1].innerHTML == tab.rows[i - 1].cells[col - 1].innerHTML) {
                        count++;
                    } else if (i > 0 && col == 0 && tab.rows[i].cells[col].innerHTML == tab.rows[i - 1].cells[col].innerHTML) {
                        count++;
                    } else {
                        if (count > 1) {
                            //合并
                            start = i - count;
                            tab.rows[start].cells[col].rowSpan = count;
                            for (var j = start + 1; j < i; j++) { //
                                tab.rows[j].removeChild(tab.rows[j].cells[col]);
                            }
                            count = 1;
                        }
                    }
                }
                if (count > 1) { //合并，最后几行相同的情况下
                    start = i - count;
                    tab.rows[start].cells[col].rowSpan = count;
                    for (var j = start + 1; j < i; j++) {
                        tab.rows[j].removeChild(tab.rows[j].cells[col]);
                    }
                }
            }
        }

        function loadingshow() {
            $('#table-container').css('background-image', 'url("../images/loading.gif")');
            $('#table-container').css('background-size', '0.8rem 0.8rem');
            $('#table-container').css('background-repeat', 'no-repeat');
            $('#table-container').css('background-position', 'center');
        }
        function loadingnone() {
            $('#table-container').css('background-image', 'none');
        }

        //报表
        var boarddata = function () {
            $('#btn_query').prop('disabled', true);
            $("#myTable>thead>tr, #yield_tbody,#myTable>tfoot>tr").empty();
            var header_key = {
                month: $('#cmb_month').val()
            };
            var pam = {};
            pam.proj_code = $('#cmb_proj_code').val();
            pam.product_code = $('#cmb_product_code').val();
            pam.header_key = JSON.stringify(header_key);
            if (pam.proj_code !== "-1") {
                loadingshow();
                $.ajax({
                    type: "POST",
                    url: api + "/ReportAction/GetErpWipReport",
                    data: pam,
                    dataType: "json",
                    success: function (dt) {
                        loadingnone();
                        $('#btn_query').prop('disabled', false);
                        var data = dt.ReturnData;
                        var table = $('#myTable');
                        var tbody = table.find('tbody');
                        $("#myTable>thead>tr, #yield_tbody,#myTable>tfoot>tr").empty();

                        // 动态生成表头
                        var headerRow = table.find('thead tr');
                        var headers = Object.keys(data[0]);
                        headers.forEach(function (header) {
                            headerRow.append('<th>' + header + '</th>');
                        });
                        // 生成表格内容
                        data.forEach(function (row, index) {
                            index++;
                            var newRow = $(`<tr class="${(index % 2) > 0 ? "ZebraNo" : "ZebraTo"}"></tr>`);
                            headers.forEach(function (header, columnindex) {
                                if (typeof row[header] === "number") {
                                    row[header] = row[header].toFixed(0);
                                }
                                newRow.append(`<td class="truncate ${columnindex <= 1 ? "ZebraTo" : null}">${row[header].replace(/\//g, '<br>')}</td>`);
                            });
                            tbody.append(newRow);
                        });
                        // 合计
                        var colspan = 5;
                        var tfootRow = table.find('tfoot tr');
                        tfootRow.append(`<th colspan="${colspan}">合计</th>`);
                        headers.forEach(function (header, columnindex) {
                            //是否日期
                            var dateRegex = /^\d{2}-\d{2}$/;
                            if (columnindex >= colspan && dateRegex.test(header)) {
                                //console.log(columnindex + "：" + header);
                                var sum = 0;
                                data.forEach(function (row, index) {
                                    sum = parseInt(row[header]) + sum;
                                });
                                tfootRow.append(`<th>${sum}</th>`);
                            }
                        });

                        //合并
                        mergeFunc("myTable");
                    }
                });
            }
        };
    </script>
</body>
</html>
